import { memo } from 'react';
import { Button, Table, Tag, Flex, TableColumnsType } from 'antd';

import Icon from '@/component/Icon';
import { getRecord } from '@/request/api/home';
import useDateFormat from '@/hooks/useDateFormat';
import useHttpRequest from '@/hooks/useHttpRequest';

import Styles from './index.module.less';

export interface DataType {
    key: number;
    url: string;
    status: number;
    date: string;
}
export type ResultRecordData = DataType & {
    id: number;
    created_at: string;
};

const format = useDateFormat();
const columns: TableColumnsType<DataType> = [
    {
        title: '地址',
        dataIndex: 'url',
        ellipsis: true,
        align: 'center',
        width: '30%',
        showSorterTooltip: false
    },
    {
        title: '状态',
        dataIndex: 'status',
        width: '30%',
        showSorterTooltip: false,
        render: (text) => (
            <Tag color={Number(text) ? '#87d068' : '#f50'}>
                {Number(text) ? '成功' : '失败'}
            </Tag>
        ),
        align: 'center'
    },
    {
        title: '时间',
        dataIndex: 'date',
        align: 'center',
        ellipsis: true,
        width: '40%',
        showSorterTooltip: false,
        sorter: (a, b) =>
            new Date(a.date).getTime() - new Date(b.date).getTime(),
        render: (text) => (
            <span>{format(new Date(text), 'mm-dd HH:MM:SS')}</span>
        )
    }
];

export default memo(() => {
    const [recordData, getRecordDataLoading, refreshRecord] = useHttpRequest<
        Array<DataType>,
        { code: number; data: Array<ResultRecordData> }
    >({
        requestCb: getRecord.bind(null, { page: 1, size: 999999 }),
        filterData: (result) =>
            result.data.map((item) => ({
                key: item.id,
                url: item.url,
                status: item.status,
                date: item.created_at
            }))
    });

    return (
        <>
            <Flex
                className={Styles.refreshWrap}
                gap="middle"
                justify="flex-end"
            >
                <Button
                    icon={<Icon name="icon-shuaxin" />}
                    loading={getRecordDataLoading}
                    onClick={refreshRecord}
                    type="primary"
                    size="small"
                >
                    刷新
                </Button>
            </Flex>
            <Table
                size="small"
                columns={columns}
                dataSource={recordData}
                pagination={{ pageSize: 5 }}
                loading={getRecordDataLoading}
                showSorterTooltip={{ target: 'sorter-icon' }}
            />
        </>
    );
});
